#!/bin/bash

# 步骤2: 配置Nginx和SSL证书

set -e

SERVER_IP="47.237.10.129"
SERVER_USER="root"
FRONTEND_DIR="/var/www/cumrbull-frontend"
API_DOMAIN="api.cumrbull.com.sg"
ADMIN_DOMAIN="admin.cumrbull.com.sg"

echo "=== 步骤2: 配置Nginx和SSL ==="

# 1. 安装Nginx和Certbot
echo "安装Nginx和Certbot..."
ssh $SERVER_USER@$SERVER_IP << 'EOF'
    # 更新包列表
    apt update
    
    # 安装Nginx
    if ! command -v nginx &> /dev/null; then
        apt install -y nginx
    fi
    
    # 安装Certbot
    if ! command -v certbot &> /dev/null; then
        apt install -y certbot python3-certbot-nginx
    fi
    
    # 创建前端目录
    mkdir -p /var/www/cumrbull-frontend
    
    # 启动Nginx
    systemctl start nginx
    systemctl enable nginx
    
    echo "Nginx和Certbot安装完成"
EOF

# 2. 部署前端文件
echo "部署管理后台前端..."
scp admin-production.html $SERVER_USER@$SERVER_IP:$FRONTEND_DIR/index.html

# 3. 上传Nginx配置
echo "配置Nginx..."
scp manual-nginx-config.conf $SERVER_USER@$SERVER_IP:/etc/nginx/conf.d/cu-mr-bull.conf

# 4. 配置防火墙
echo "配置防火墙..."
ssh $SERVER_USER@$SERVER_IP << 'EOF'
    # 配置UFW防火墙
    ufw allow 22
    ufw allow 80
    ufw allow 443
    ufw --force enable
    
    echo "防火墙配置完成"
EOF

# 5. 测试Nginx配置并重启
echo "测试Nginx配置..."
ssh $SERVER_USER@$SERVER_IP << 'EOF'
    # 测试Nginx配置
    nginx -t
    
    if [ $? -eq 0 ]; then
        echo "Nginx配置正确，重启服务..."
        systemctl reload nginx
    else
        echo "Nginx配置错误！"
        exit 1
    fi
EOF

# 6. 获取SSL证书
echo "获取SSL证书..."
ssh $SERVER_USER@$SERVER_IP << EOF
    # 获取SSL证书
    certbot --nginx -d $API_DOMAIN -d $ADMIN_DOMAIN --non-interactive --agree-tos --email admin@cumrbull.com.sg
    
    # 设置自动续期
    (crontab -l 2>/dev/null; echo "0 12 * * * /usr/bin/certbot renew --quiet") | crontab -
    
    echo "SSL证书配置完成"
EOF

echo "=== Nginx和SSL配置完成 ==="
echo "下一步: 运行 ./deploy-step3-start.sh 启动应用服务"